package cn.hc.mq.boot;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.Environment;
import org.springframework.util.StringUtils;

import javax.servlet.ServletContext;
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * @author huangchao E-mail:fengquan8866@163.com
 * @version 创建时间：2024/9/22 21:51
 */
@SpringBootApplication
@Slf4j
public class RocketMqStarter {

    public static void main(String[] args) {
        ConfigurableApplicationContext ctx = SpringApplication.run(RocketMqStarter.class, args);
        print(ctx);
    }

    private static void print(ConfigurableApplicationContext ctx) {
        Environment env = ctx.getEnvironment();

        String address;
        try {
            address = InetAddress.getLocalHost().getHostAddress();
        } catch (UnknownHostException e) {
            address = "";
        }

        String name = env.getProperty("spring.application.name");
        String protocol = env.getProperty("server.ssl.key-store") != null ? "https" : "http";
        String port = env.getProperty("local.server.port");

        ServletContext context;
        try {
            context = ctx.getBean(ServletContext.class);
        } catch (Exception e) {
            context = null;
        }
        String path = context == null ? null : context.getContextPath();
        if (StringUtils.hasText(path) && !path.startsWith("/")) {
            path = "/" + path;
        }

        String profiles = String.join( ",", env.getActiveProfiles());

        StringBuilder builder = new StringBuilder();
        builder.append("\n----------------------------------------------------------\n");
        builder.append("Application '{}' is running! Access URLs:\n\t");
        builder.append("Local:\t\t{}://localhost:{}{}\n\t");
        builder.append("External:\t{}://{}:{}{}\n\t");
        builder.append("Profile(s):\t{}");
        builder.append("\n----------------------------------------------------------");

        log.info(builder.toString(), name, protocol, port, path, protocol, address, port, path, profiles);
    }
}
